package com.demo.villageresidence.controller;

import com.demo.villageresidence.dto.Result;
import com.demo.villageresidence.pojo.Like;
import com.demo.villageresidence.pojo.Remark;
import com.demo.villageresidence.pojo.User;
import com.demo.villageresidence.service.LikeService;
import com.demo.villageresidence.service.RemarkService;
import com.demo.villageresidence.service.UserService;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/remark")
public class RemarkController {

    @Autowired
    private RemarkService remarkService;

    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;


    @GetMapping("getRemarkAll/{userId}")
    private Result getRemarkAll(@PathVariable("userId") Integer userId){
        List<Remark> remarkList = remarkService.query().eq("remark_pid", -1).list();
        System.out.println(remarkList);
        if (userId == -1){
            return setRemarkList(null, remarkList);
        }
        return setRemarkList(userId, remarkList);
    }

    /*
     * 根据点赞最高的评论获取评论
     *
     */
    @GetMapping("getRemarkByLikeNumber/{userId}")
    public Result getRemarkByLikeNumber(@PathVariable("userId") Integer userId){
        List<Remark> remarkList = remarkService.query().eq("remark_pid", -1).orderByDesc("remark_like_number").list();
        if (userId == -1){
            return setRemarkList(null, remarkList);
        }
        return setRemarkList(userId, remarkList);

    }

    /*
     * 根据评论时间获取评论
     */
    @GetMapping("getRemarkByRemarkTime/{userId}")
    public Result getRemarkByRemarkTime(@PathVariable("userId") Integer userId){
        List<Remark> remarkList = remarkService.query().eq("remark_pid", -1).orderByDesc("remark_time").list();
        if (userId == -1){
            return setRemarkList(null, remarkList);
        }
        return setRemarkList(userId, remarkList);
    }

    private Result setRemarkList(@PathVariable("userId") Integer userId, List<Remark> remarkList) {
        remarkList.forEach(remark->{
            // 判断用户对某条评论是否点赞
            isLike(userId, remark);
            remark.setUser(userService.getById(remark.getUserId()));
            List<Remark> remarkPidList = remarkService.
                    query()
                    .eq("remark_pid", remark.getRemarkId())
                    .orderByDesc("remark_like_number")
                    .orderByDesc("remark_time")
                    .list();
            if (remarkPidList.size() != 0){
                remark.setRemarkReplyNumber(remarkPidList.size());
                remark.setRemarkList(remarkPidList);
                remark.getRemarkList().forEach(remark1 -> {
                    remark1.setUser(userService.getById(remark1.getUserId()));
                    isLike(userId, remark1);
                    if (remark1.getUser() == null) {
                        User user = new User();
                        user.setUserName("用户已注销");
                        user.setRealName("用户已注销");
                        user.setUserId(-2);
                        user.setUserAvatar("https://img-blog.csdnimg.cn/20200527162905959.png");
                        remark1.setUser(user);
                    }
                });
            }else {
                remark.setRemarkList(null);
            }

        });
        return Result.ok(remarkList);
    }

    private void isLike(@PathVariable("userId") Integer userId, Remark remark) {
        if (userId == null) {
            remark.setIsLike(0);
            return;
        }
        Like like1 = likeService.query().eq("remark_id", remark.getRemarkId()).eq("user_id", userId).one();
        if (like1 == null){
            remark.setIsLike(0);
        }
        else{
            if (like1.getIsLike() == null || like1.getIsLike() == 0)
                remark.setIsLike(0);
            else if (like1.getIsLike() == 1)
                remark.setIsLike(1);
        }
    }

    @PostMapping("addRemark")
    private Result addRemark(@RequestBody Remark remark) {
        remark.setRemarkPid(-1);
        remark.setIsDelete(0);
        remark.setRemarkTime(LocalDateTime.now());
        System.out.println(remark);
        if (remarkService.save(remark)) {
            return Result.ok("发送成功");
        } else {
            return Result.fail("回复失败");
        }
    }

    @PostMapping("addReply")
    private Result addReply(@RequestBody Remark remark) {
        remark.setIsDelete(0);
        remark.setRemarkTime(LocalDateTime.now());
        if (remarkService.save(remark)) {
            return Result.ok("发送成功");
        } else {
            return Result.fail("回复失败");
        }
    }

    /**
     * 点赞
     */
    @PutMapping("updateRemarkLike")
    private Result updateRemarkLike(@RequestParam Integer remarkId, @RequestParam Integer userId) {
        // 1.判断当前登录用户是否已经点赞
        Like like = likeService.query().eq("remark_id", remarkId).eq("user_id", userId).one();
        if (like != null) {
            if (like.getIsLike() == 1) {
                // 已经点赞，取消点赞
                like.setIsLike(0);
                likeService.updateById(like);
                remarkService.update().setSql("remark_like_number = remark_like_number - 1").eq("remark_id", remarkId).update();
                return Result.ok("取消点赞");
            }else {
                // 没有点赞，添加点赞
                like.setIsLike(1);
                remarkService.update().setSql("remark_like_number = remark_like_number + 1").eq("remark_id", remarkId).update();
                likeService.updateById(like);
                return Result.ok("点赞成功");
            }
        }else {
            // 2.没有点赞，添加点赞
            like = new Like();
            like.setRemarkId(remarkId);
            like.setUserId(userId);
            like.setIsLike(1);
            likeService.save(like);
            if (remarkService.getById(remarkId).getRemarkLikeNumber() == null || remarkService.getById(remarkId).getRemarkLikeNumber() == 0) {
                remarkService.update().setSql("remark_like_number = 1").eq("remark_id", remarkId).update();}
            else {
                remarkService.update().setSql("remark_like_number = remark_like_number + 1").eq("remark_id", remarkId).update();
            }
            return Result.ok("点赞成功");
        }


    }





}
